package com.example.flutter_demo2.plugins

import android.app.Activity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel


const val CHANNEL_METHOD = "channel_method"
const val CHANNEL_EVENT = "channel_event"

abstract class BasePlugin(
    private val methodChannelName: String,
    private var eventChannelName: String = ""
) : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware, EventChannel.StreamHandler {

    private var mEventSink: EventChannel.EventSink? = null

    protected lateinit var mRootActivity: Activity

    // check mRootActivity initialized
    val isActivityInitialized get() = this::mRootActivity.isInitialized

    final override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val methodChannel = MethodChannel(binding.binaryMessenger, methodChannelName)
        methodChannel.setMethodCallHandler(this)
        if (eventChannelName.isNotEmpty()) {
            val eventChannel = EventChannel(binding.binaryMessenger, eventChannelName)
            eventChannel.setStreamHandler(this)
        }
    }

    final override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    }

    abstract override fun onMethodCall(call: MethodCall, result: MethodChannel.Result)

    final override fun onDetachedFromActivity() {
    }

    final override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    final override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.mRootActivity = binding.activity
    }

    final override fun onDetachedFromActivityForConfigChanges() {
    }

    final override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        this.mEventSink = events
    }

    final override fun onCancel(arguments: Any?) {
    }

    fun sendEvent2flutter(eventJson: String) {
        mEventSink?.success(eventJson)
    }
}

data class ChannelEvent(var title: String, var content: String, var content1: String = "")